import Vue from 'vue'
import VueRouter from 'vue-router'

import { getItem } from '../utils/storage'

// 配置二级路由
const Article = () => import('../views/Article.vue')
const Like = () => import('../views/Like.vue')
const Collect = () => import('../views/Collect.vue')
const User = () => import('../views/User.vue')

const Detail = () => import('../views/Detail.vue')
const Layout = () => import('../views/Layout.vue')
const Login = () => import('../views/Login.vue')
const Register = () => import('../views/Register.vue')
Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    {
      path: '/',
      component: Layout,
      redirect: '/article',
      children: [
        { path: '/article', component: Article },
        { path: '/like', component: Like },
        { path: '/collect', component: Collect },
        { path: '/user', component: User }
      ]
    },
    {
      path: '/detail/:id',
      component: Detail
    },
    {
      path: '/login',
      component: Login
    },
    {
      path: '/register',
      component: Register
    }
  ]
})
router.beforeEach((to, from, next) => {
  const token = getItem()
  if (token) {
    next()
  } else {
    const whiteArr = ['/login', '/register']
    if (whiteArr.includes(to.path)) {
      next()
    }
    next('/login')
  }
})

export default router
